package com.imooc.controller;

import com.imooc.converter.OrderForm2OrderDTOConverter;
import com.imooc.dto.OrderDTO;
import com.imooc.enums.ResultEnum;
import com.imooc.exception.SellException;
import com.imooc.form.OrderForm;
import com.imooc.service.BuyerService;
import com.imooc.service.OrderService;
import com.imooc.utils.ResultVOUtil;
import com.imooc.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * FileName: BuyerOrderController.java
 * Description: 买家端订单controller
 *
 * @author HuangRI(874668739 @ qq.com)
 * @version 1.0
 * @date 2020/12/23
 */
@RestController
@Slf4j
@RequestMapping("/buyer/order")
public class BuyerOrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private BuyerService buyerService;

    /**
     * 创建订单
     * {
     *  name: "张三"
     *  phone: "18868822111"
     *  address: "慕课网总部"
     *  openid: "ew3euwhd7sjw9diwkq" //用户的微信openid
     *  items: [{
     *      productId: "1423113435324",
     *      productQuantity: 2 //购买数量
     *  }]
     * }
     * @return
     */
    @PostMapping("/create")
    public ResultVO<Map<String, String>> create(@Valid OrderForm orderForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.error("【创建订单】前端请求参数不正确，orderForm={}", orderForm);
            throw new SellException(ResultEnum.PARAM_ERROR.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }

        OrderDTO orderDTO = OrderForm2OrderDTOConverter.convert(orderForm);
        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
            log.error("【创建订单】购物车为空, items={}", orderForm.getItems());
            throw new SellException(ResultEnum.CART_EMPTY);
        }
        OrderDTO createResult = this.orderService.create(orderDTO);

        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("orderId", createResult.getOrderId());

        return ResultVOUtil.ok(resultMap);
    }

    /**
     * 订单列表
     * @param openid 买家openid
     * @param page 当前页码
     * @param size 每页可显示最大数
     * @return ResultVO<OrderDTO>
     */
    @GetMapping("/list")
    public ResultVO<OrderDTO> list(@RequestParam("openid") String openid,
                                   @RequestParam(value = "page", defaultValue = "0") Integer page,
                                   @RequestParam(value = "size", defaultValue = "#{buyerConfig.page.size}") Integer size) {
        if (StringUtils.isBlank(openid)) {
            log.error("【买家订单列表查询】openid不能为空");
            throw new SellException(ResultEnum.PARAM_ERROR.getCode(), "买家openid不能为空");
        }

        PageRequest pageRequest = PageRequest.of(page, size);
        Page<OrderDTO> orderDTOPage = this.orderService.findList(openid, pageRequest);
        return ResultVOUtil.ok(orderDTOPage.getContent());
    }

    /**
     * 订单详情
     * @param openid 买家openid
     * @param orderId 订单ID
     * @return ResultVO<OrderDTO>
     */
    @GetMapping("/detail")
    public ResultVO<OrderDTO> detail(@RequestParam("openid") String openid,
                                     @RequestParam("orderId") String orderId) {
        if (StringUtils.isBlank(openid)) {
            log.error("【买家订单详情查询】openid不能为空");
            throw new SellException(ResultEnum.PARAM_ERROR.getCode(), "openid不能为空");
        } else if (StringUtils.isBlank(orderId)) {
            log.error("【买家订单详情查询】orderId不能为空");
            throw new SellException(ResultEnum.PARAM_ERROR.getCode(), "orderId不能为空");
        }

        OrderDTO orderDTO = this.buyerService.findOneOrder(openid, orderId);
        return ResultVOUtil.ok(orderDTO);
    }

    @PostMapping("/cancel")
    public ResultVO cancel(@RequestParam("openid") String openid,
                           @RequestParam("orderId") String orderId) {
        if (StringUtils.isBlank(openid)) {
            log.error("【买家订单取消】openid不能为空");
            throw new SellException(ResultEnum.PARAM_ERROR.getCode(), "openid不能为空");
        } else if (StringUtils.isBlank(orderId)) {
            log.error("【买家订单取消】orderId不能为空");
            throw new SellException(ResultEnum.PARAM_ERROR.getCode(), "orderId不能为空");
        }

        this.buyerService.cancelOrder(openid, orderId);
        return ResultVOUtil.ok();
    }
}
